﻿using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HN.WxPayApiV3Partner.Model
{
    public static class V3Utils
    {
        /// <summary>
        /// 通知地址数据解密
        /// </summary>
        /// <param name="v3NotifyModel"></param>
        /// <returns></returns>
        public static string AesGcmDecrypt(V3NotifyModel v3NotifyModel)
        {
            GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
            AeadParameters aeadParameters = new AeadParameters(
                new KeyParameter(Encoding.UTF8.GetBytes(V3Const.APIV3Key)),
                128,
                Encoding.UTF8.GetBytes(v3NotifyModel.resource.nonce),
                Encoding.UTF8.GetBytes(v3NotifyModel.resource.associated_data));
            gcmBlockCipher.Init(false, aeadParameters);
            byte[] data = Convert.FromBase64String(v3NotifyModel.resource.ciphertext);
            byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
            int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
            gcmBlockCipher.DoFinal(plaintext, length);
            return Encoding.UTF8.GetString(plaintext);
        }
        /// <summary>
        /// APP错误日志
        /// </summary>
        /// <param name="LogDirPath"></param>
        /// <param name="writeStr"></param>
        public static void AppLog(string writeStr)
        {
            FileStream fs = null;
            string filename = System.DateTime.Now.ToString("yyyyMMdd") + ".txt";
            string strpath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\";
            string filepath = strpath + filename;
            try
            {
                if (!Directory.Exists(strpath))
                {
                    Directory.CreateDirectory(strpath);
                }

                if (!File.Exists(filepath))
                {
                    fs = File.Create(System.IO.Path.Combine(strpath, filename));
                }
                else
                {
                    fs = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }

                byte[] str = System.Text.Encoding.Default.GetBytes(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "    " + writeStr + "\r\n");


                fs.Write(str, 0, str.Length);   //写入文件
                fs.Flush();     //清空缓冲区
            }
            catch (IOException ex)
            {

            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 根据日期和随机码生成订单号
        /// </summary>
        /// <returns></returns>
        public static string GetOrderNumber()
        {
            string num = DateTime.Now.ToString("yyMMddHHmmssfffff");//yyyyMMddHHmmssms
            return num + Number(2, true).ToString();
        }
        /// <summary>
        /// 生成随机数字
        /// </summary>
        /// <param name="Length">生成长度</param>
        /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
        /// <returns></returns>
        public static string Number(int Length, bool Sleep)
        {
            if (Sleep)
                System.Threading.Thread.Sleep(3);
            string result = "";
            System.Random random = new Random();
            for (int i = 0; i < Length; i++)
            {
                result += random.Next(10).ToString();
            }
            return result;
        }
        /**
  * 生成时间戳，标准北京时间，时区为东八区，自1970年1月1日 0点0分0秒以来的秒数
   * @return 时间戳
  */
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /**
        * 生成随机串，随机串包含字母或数字
        * @return 随机串
        */
        public static string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }

    }
}
